﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration.Claims;
using Microsoft.IdentityModel.Claims;
using System.Web;
using Microsoft.SharePoint.Administration;

using CNRS.CCP.Config;

namespace CNRS.CCP.Connector
{
    public class ClaimsHelper
    {
        // TODO : remove
		/// <summary>
        /// Recupere le claim associé à l'utilisateur connecté
        /// </summary>
        /// <param name="claimType">ex : "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"</param>
        public static string GetClaimValueInUserClaims(string claimType)
        {
            try
            {
                // Get the claims
                IClaimsPrincipal cp = HttpContext.Current.User as IClaimsPrincipal;
                if (cp != null)
                {
                    IClaimsIdentity ci = (IClaimsIdentity)cp.Identity;
                    foreach (Claim c in ci.Claims)
                    {
                        if (c.ClaimType.ToString().ToLower() == claimType.ToLower())
                            return c.Value.ToString();
                    }
                }

                return null;
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                LogHelper.Log(LogCategorie.ClaimsHelper, "error in GetClaimValueInUserClaims : " + ex, TraceSeverity.Unexpected);
                return null;
            }
        }



        /// <summary>
        /// Remove claim information from an user or role
        /// ex : i:05.t|mgiadfs.aresu.dsi.cnrs.fr|jean-marie.thia@dsi.cnrs.fr => jean-marie.thia@dsi.cnrs.fr
        /// </summary>
        /// <param name="encodedClaim">Encoded claim</param>
        /// <param name="force">if true, return a value even if it wasn't a claim</param>
        /// <returns>Decoded claim</returns>
        public static string GetDecodedClaim(string encodedClaim, bool force)
        {
            string userName = string.Empty;

            if (encodedClaim.Contains("0#.w"))
            {
                string[] strArr = encodedClaim.Split('|');
                userName = strArr[1];
            }
            else
            {
                int userPipe = encodedClaim.LastIndexOf("|");
                if (userPipe > -1)
                    userName = encodedClaim.Substring(userPipe + 1);
                else if (force)
                    userName = encodedClaim;
            }

            return userName;
        }
    }



}
